import { useRef } from 'react'
import { Color } from './color'
import Handler from './Handler'
import Transform from './Transform'
import { useColorDrag } from './useColorDrag'
import { calculateColor, calculateOffset } from './utils'

const Palettle: React.FC<{
  color: Color
  onChange?: (color: Color) => void
}> = ({ color, onChange }) => {
  const transformRef = useRef<HTMLDivElement>(null)
  const containerRef = useRef<HTMLDivElement>(null)

  const [offset, dragStartHandle] = useColorDrag({
    containerRef,
    color,
    targetRef: transformRef,
    calculate: () => {
      return calculateOffset(containerRef, transformRef, color)
    },
    onDragChange: (offsetValue) => {
      const newColor = calculateColor({
        containerRef,
        targetRef: transformRef,
        offset: offsetValue,
        color
      })
      onChange?.(newColor)
    }
  })
  return (
    <div
      className="color-picker-panel-palette"
      ref={containerRef}
      onMouseDown={dragStartHandle}
    >
      <Transform ref={transformRef} offset={offset}>
        <Handler color={color.toRgbString()} />
      </Transform>
      <div
        className="color-picker-panel-palette-main"
        style={{
          backgroundColor: `hsl(${color.toHsl().h},100%, 50%)`,
          backgroundImage:
            'linear-gradient(0deg, #000, transparent),linear-gradient(90deg, #fff, hsla(0, 0%, 100%, 0))'
        }}
      />
    </div>
  )
}

export default Palettle
